import { routerRedux } from 'dva/router';

import { stringify } from 'qs';

import { Login, Logout , getLoginCaptcha} from '@/services/system/api_system_login';

import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload , callback }, { call, put }) {
      const response = yield call(Login, payload);
      //console.log(response)

      // Login successfully
      if (response.success === true) {

        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });

        localStorage.setItem('antd-pro-authority', JSON.stringify(response.datarecord.roles))
        localStorage.setItem('antd-token-authority', response.datarecord.token);
        localStorage.setItem('antd-token-username', response.datarecord.username);

        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;


        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        
        yield put(routerRedux.replace(redirect || '/'));

      }


     if (callback) callback(response);

    },

    *getCaptcha({ payload }, { call }) {
      yield call(getLoginCaptcha, payload);
    },

    *logout(_, { put }) {

      //yield call(Logout, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      const { redirect } = getPageQuery();
      // redirect
      if (window.location.pathname !== '/user/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          })
        );
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};
